package org.jeecg.hr.service.impl;

import java.io.Serializable;
import java.util.Collection;

import javax.transaction.Transactional;

import org.jeecg.hr.entity.InsuranceTemplate;
import org.jeecg.hr.entity.InsuranceTemplateDetail;
import org.jeecg.hr.mapper.InsuranceTemplateDetailMapper;
import org.jeecg.hr.mapper.InsuranceTemplateMapper;
import org.jeecg.hr.service.InsuranceTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
public class InsuranceTemplateServiceImpl extends ServiceImpl<InsuranceTemplateMapper, InsuranceTemplate> implements InsuranceTemplateService {

	@Autowired
	private InsuranceTemplateMapper insuranceTemplateMapper;
	@Autowired
	private InsuranceTemplateDetailMapper insuranceTemplateDetailMapper;
	
	@Override
	@Transactional
	public void delInsuranceTemplate(String id) {
		InsuranceTemplate insuranceTemplate = insuranceTemplateMapper.selectById(id);
		insuranceTemplateDetailMapper.deleteByTemplateCode(insuranceTemplate.getTemplateCode());
		insuranceTemplateMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			InsuranceTemplate salaryTemplate = insuranceTemplateMapper.selectById(id);
			insuranceTemplateDetailMapper.deleteByTemplateCode(salaryTemplate.getTemplateCode());
			insuranceTemplateMapper.deleteById(id);
		}
	}
	
	@Override
	@Transactional
	public void saveInsuranceTemplateWithDetail(InsuranceTemplate insuranceTemplate) {
		insuranceTemplateMapper.insert(insuranceTemplate);
		if(insuranceTemplate.getInsuranceTemplateDetails() != null && insuranceTemplate.getInsuranceTemplateDetails().size() > 0) {
			for(InsuranceTemplateDetail entity:insuranceTemplate.getInsuranceTemplateDetails()) {
				entity.setTemplateCode(insuranceTemplate.getTemplateCode());
				insuranceTemplateDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateInsuranceTemplateWithDetail(InsuranceTemplate insuranceTemplate) {
		insuranceTemplateMapper.updateById(insuranceTemplate);
		
		//1.先删除子表数据
		insuranceTemplateDetailMapper.deleteByTemplateCode(insuranceTemplate.getTemplateCode());
		
		//2.子表数据重新插入
		if(insuranceTemplate.getInsuranceTemplateDetails() !=null && insuranceTemplate.getInsuranceTemplateDetails().size()>0) {
			for(InsuranceTemplateDetail entity : insuranceTemplate.getInsuranceTemplateDetails()) {
				entity.setTemplateCode(insuranceTemplate.getTemplateCode());
				insuranceTemplateDetailMapper.insert(entity);
			}
		}
	}
	
}
